<script setup lang="ts">
  import { ref, onMounted, computed, watch, onUnmounted } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import type { Blog, Category, Tag } from '@/types/api'
  import { tree as getCategoryTree } from '@/api/category'
  import { page as getBlogPage } from '@/api/blog'
  import { list as getTagList } from '@/api/tag'
  import CategoryTreeNode from '@/views/categories/components/CategoryTreeNode.vue'

  const router = useRouter()
  const route = useRoute()
  const loading = ref(true)
  const categories = ref<Category[]>([])
  const selectedCategory = ref<Category | null>(null)
  const expandedCategories = ref<Set<string>>(new Set())
  const categoryBlogs = ref<Blog[]>([])
  const blogsLoading = ref(false)
  const searchKeyword = ref('')
  const sortType = ref<number>(-1) // -1: 时间倒序, 1: 时间正序, -2: 阅读倒序, 2: 阅读正序
  const recentBlogs = ref<Blog[]>([])
  const popularTags = ref<Tag[]>([])
  const showSortDropdown = ref(false)

  // 排序选项
  const sortOptions = [
    { value: -1, label: '最新发布', icon: '🆕' },
    { value: 1, label: '最早发布', icon: '⏰' },
    { value: -2, label: '最多阅读', icon: '👁️' },
    { value: 2, label: '最少阅读', icon: '📖' },
  ]

  // 分页信息
  const pagination = ref({
    current: 1,
    pageSize: 10,
    total: 0,
  })

  // 扁平化分类列表（用于快速查找）
  const flatCategories = computed(() => {
    const flatten = (cats: Category[], depth = 0): (Category & { depth: number })[] => {
      const result: (Category & { depth: number })[] = []
      for (const cat of cats) {
        result.push({ ...cat, depth })
        if (cat.children && cat.children.length > 0) {
          result.push(...flatten(cat.children, depth + 1))
        }
      }
      return result
    }
    return flatten(categories.value)
  })

  // 获取分类路径
  const getCategoryPath = (categoryId: string): Category[] => {
    const findPath = (
      cats: Category[],
      targetId: string,
      path: Category[] = []
    ): Category[] | null => {
      for (const cat of cats) {
        const currentPath = [...path, cat]
        if (cat.id === targetId) {
          return currentPath
        }
        if (cat.children && cat.children.length > 0) {
          const result = findPath(cat.children, targetId, currentPath)
          if (result) return result
        }
      }
      return null
    }
    return findPath(categories.value, categoryId) || []
  }

  // 切换分类展开状态
  const toggleCategory = (categoryId: string) => {
    const newExpanded = new Set(expandedCategories.value)
    if (newExpanded.has(categoryId)) {
      newExpanded.delete(categoryId)
    } else {
      newExpanded.add(categoryId)
    }
    expandedCategories.value = newExpanded
  }

  // 选择分类
  const selectCategory = (category: Category) => {
    selectedCategory.value = category
    // 更新URL
    router.replace({
      path: route.path,
      query: { ...route.query, categoryId: category.id },
    })
    // 加载该分类的文章
    loadCategoryBlogs()
  }

  // 获取分类图标
  const getCategoryIcon = () => {
    return '📁' // 所有分类都使用文件夹图标
  }

  // 过滤掉博客数量为0的分类（递归过滤子分类）
  const filterCategoriesWithCount = (cats: Category[]): Category[] => {
    return cats
      .filter(cat => (cat.count || 0) > 0) // 过滤掉count为0的分类
      .map(cat => ({
        ...cat,
        children: cat.children ? filterCategoriesWithCount(cat.children) : undefined,
      }))
      .filter(cat => (cat.count || 0) > 0 || (cat.children && cat.children.length > 0)) // 如果有子分类，即使自己count为0也保留
  }

  // 获取分类及其所有子分类的ID列表
  const getCategoryAndChildrenIds = (category: Category): string[] => {
    const ids: string[] = [category.id.toString()]

    if (category.children && category.children.length > 0) {
      for (const child of category.children) {
        ids.push(...getCategoryAndChildrenIds(child))
      }
    }

    return ids
  }

  // 加载分类数据
  const loadCategories = async () => {
    try {
      const response = await getCategoryTree()
      const processedCategories = (response || []).map(category => ({
        ...category,
        color: category.color || '#409EFF',
      }))

      // 过滤掉博客数量为0的分类
      categories.value = filterCategoriesWithCount(processedCategories)

      // 默认展开第一层分类
      categories.value.forEach(cat => {
        if (cat.children && cat.children.length > 0) {
          expandedCategories.value.add(cat.id)
        }
      })

      // 从URL获取选中的分类ID，或默认选择第一个分类
      const categoryId = route.query.categoryId as string
      if (categoryId) {
        const category = flatCategories.value.find(cat => cat.id === categoryId)
        if (category) {
          selectedCategory.value = category
        }
      }

      if (!selectedCategory.value && flatCategories.value.length > 0) {
        selectedCategory.value = flatCategories.value[0]
      }

      if (selectedCategory.value) {
        loadCategoryBlogs()
      }
    } catch (error) {
      console.error('加载分类失败:', error)
    }
  }

  // 加载分类下的文章
  const loadCategoryBlogs = async () => {
    if (!selectedCategory.value) return

    try {
      blogsLoading.value = true

      // 获取当前分类及其所有子分类的ID
      const categoryIds = getCategoryAndChildrenIds(selectedCategory.value)

      const response = await getBlogPage({
        categories: categoryIds, // 传入当前分类及其所有子分类的ID
        keyword: searchKeyword.value || undefined,
        sort: sortType.value,
        pageNum: pagination.value.current,
        pageSize: pagination.value.pageSize,
      })

      categoryBlogs.value = response?.records || []
      pagination.value.total = response?.total || 0
    } catch (error) {
      console.error('加载分类文章失败:', error)
    } finally {
      blogsLoading.value = false
    }
  }

  // 跳转到文章详情
  const handleBlogClick = (blog: Blog) => {
    router.push(`/articles/${blog.id}`)
  }

  // 搜索文章
  const handleSearch = () => {
    pagination.value.current = 1
    loadCategoryBlogs()
  }

  // 分页改变
  const handlePageChange = (page: number) => {
    pagination.value.current = page
    loadCategoryBlogs()
  }

  // 格式化日期
  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('zh-CN')
  }

  // 监听选中分类变化
  watch(selectedCategory, () => {
    if (selectedCategory.value) {
      pagination.value.current = 1
      searchKeyword.value = ''
    }
  })

  // 加载最新文章
  const loadRecentBlogs = async () => {
    try {
      const response = await getBlogPage({
        pageNum: 1,
        pageSize: 6,
        sort: -1, // 发布时间倒序
      })
      recentBlogs.value = response?.records || []
    } catch (error) {
      console.error('加载最新文章失败:', error)
    }
  }

  // 加载热门标签
  const loadPopularTags = async () => {
    try {
      const response = await getTagList()
      // 按文章数量排序，取前12个
      popularTags.value = (response || [])
        .filter(tag => tag.count > 0)
        .sort((a, b) => (b.count || 0) - (a.count || 0))
        .slice(0, 12)
        .map(tag => ({
          ...tag,
          color: tag.color || '#409EFF',
        }))
    } catch (error) {
      console.error('加载热门标签失败:', error)
    }
  }

  // 切换排序下拉菜单
  const toggleSortDropdown = () => {
    showSortDropdown.value = !showSortDropdown.value
  }

  // 点击外部关闭下拉菜单
  const handleClickOutside = (event: Event) => {
    const target = event.target as HTMLElement
    if (!target.closest('.custom-select')) {
      showSortDropdown.value = false
    }
  }

  // 获取排序选项文本
  const getSortText = (sort: number) => {
    switch (sort) {
      case -1:
        return '最新发布'
      case 1:
        return '最早发布'
      case -2:
        return '最多阅读'
      case 2:
        return '最少阅读'
      default:
        return '排序'
    }
  }

  // 处理排序选择
  const handleSortSelect = (sort: number) => {
    sortType.value = sort
    pagination.value.current = 1
    loadCategoryBlogs()
    toggleSortDropdown()
  }

  onMounted(async () => {
    document.addEventListener('click', handleClickOutside)

    loading.value = true
    try {
      await Promise.all([loadCategories(), loadRecentBlogs(), loadPopularTags()])
    } finally {
      loading.value = false
    }
  })

  // 清理事件监听
  onUnmounted(() => {
    document.removeEventListener('click', handleClickOutside)
  })
</script>

<template>
  <div class="category-list-page">
    <div class="container">
      <!-- 页面头部 -->
      <div class="page-header">
        <h1 class="page-title">📁 分类浏览</h1>
        <p class="page-subtitle">按分类层级结构浏览技术文章</p>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <p>正在加载分类数据...</p>
      </div>

      <!-- 主要内容 -->
      <div v-else class="main-content">
        <!-- 左侧：分类层级树 -->
        <div class="categories-sidebar">
          <div class="sidebar-header">
            <h3>📂 分类结构</h3>
            <p class="category-count">共 {{ flatCategories.length }} 个分类</p>
          </div>

          <div class="categories-tree">
            <!-- 递归渲染分类树 -->
            <CategoryTreeNode
              v-for="category in categories"
              :key="category.id"
              :category="category"
              :depth="0"
              :selected-id="selectedCategory?.id || ''"
              :expanded-categories="expandedCategories"
              @select="selectCategory"
              @toggle="toggleCategory"
            />
          </div>
        </div>

        <!-- 右侧：分类详情面板 -->
        <div class="category-detail-panel">
          <div v-if="selectedCategory" class="detail-content">
            <!-- 分类信息区域 -->
            <div class="category-info-section">
              <div class="category-header">
                <div class="category-title">
                  <span class="category-icon-large">
                    {{ getCategoryIcon() }}
                  </span>
                  <h2>{{ selectedCategory.name }}</h2>
                </div>

                <div class="category-path">
                  <span class="path-label">路径：</span>
                  <span
                    v-for="(pathCat, index) in getCategoryPath(selectedCategory.id)"
                    :key="pathCat.id"
                    class="path-item"
                    :class="{ clickable: index < getCategoryPath(selectedCategory.id).length - 1 }"
                    @click="
                      index < getCategoryPath(selectedCategory.id).length - 1
                        ? selectCategory(pathCat)
                        : null
                    "
                  >
                    <span v-if="index > 0" class="path-separator">></span>
                    {{ pathCat.name }}
                  </span>
                </div>

                <div class="category-stats">
                  <div class="stat-item">
                    <span class="stat-label">直属文章</span>
                    <span class="stat-value">{{ selectedCategory.currentCount || 0 }}篇</span>
                  </div>
                  <div class="stat-item">
                    <span class="stat-label">总文章数</span>
                    <span class="stat-value">{{ selectedCategory.count || 0 }}篇</span>
                  </div>
                  <div v-if="selectedCategory.children?.length" class="stat-item">
                    <span class="stat-label">子分类</span>
                    <span class="stat-value">{{ selectedCategory.children.length }}个</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 子分类网格区域 -->
            <div v-if="selectedCategory.children?.length" class="subcategories-section">
              <h3 class="section-title">子分类 ({{ selectedCategory.children.length }}个)</h3>
              <div class="subcategories-grid">
                <div
                  v-for="subCategory in selectedCategory.children"
                  :key="subCategory.id"
                  class="subcategory-card"
                  :style="{ '--category-color': subCategory.color || selectedCategory.color }"
                  @click="selectCategory(subCategory)"
                >
                  <div class="subcategory-icon">
                    {{ getCategoryIcon() }}
                  </div>
                  <div class="subcategory-info">
                    <h4 class="subcategory-name">{{ subCategory.name }}</h4>
                    <span class="subcategory-count">{{ subCategory.count || 0 }}篇文章</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 文章列表区域 -->
            <div class="articles-section">
              <div class="articles-header">
                <h3 class="section-title">分类文章 ({{ pagination.total }}篇)</h3>

                <div class="articles-controls">
                  <!-- 搜索框 -->
                  <div class="search-box">
                    <input
                      v-model="searchKeyword"
                      type="text"
                      placeholder="搜索文章..."
                      @keyup.enter="handleSearch"
                    />
                    <button @click="handleSearch">🔍</button>
                  </div>

                  <!-- 排序选择 -->
                  <div class="sort-select">
                    <div class="custom-select" @click="toggleSortDropdown">
                      <div class="select-trigger">
                        <span class="select-text">{{ getSortText(sortType) }}</span>
                        <span class="select-arrow" :class="{ open: showSortDropdown }">▼</span>
                      </div>
                      <div v-if="showSortDropdown" class="select-dropdown">
                        <div
                          v-for="option in sortOptions"
                          :key="option.value"
                          class="select-option"
                          :class="{ selected: sortType === option.value }"
                          @click="handleSortSelect(option.value)"
                        >
                          <span class="option-icon">{{ option.icon }}</span>
                          <span class="option-text">{{ option.label }}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 文章列表 -->
              <div class="articles-list">
                <div v-if="blogsLoading" class="articles-loading">
                  <div class="loading-spinner"></div>
                  <p>正在加载文章...</p>
                </div>

                <div v-else-if="categoryBlogs.length === 0" class="articles-empty">
                  <p>该分类下暂无文章</p>
                </div>

                <div v-else class="articles-items">
                  <div
                    v-for="blog in categoryBlogs"
                    :key="blog.id"
                    class="article-item"
                    @click="handleBlogClick(blog)"
                  >
                    <div class="article-content">
                      <h4 class="article-title">{{ blog.title }}</h4>
                      <p class="article-summary">{{ blog.summary || '暂无摘要' }}</p>
                      <div class="article-meta">
                        <span class="article-category">{{ blog.category?.name }}</span>
                        <span class="article-date">{{ formatDate(blog.pushTime) }}</span>
                        <span class="article-stats">
                          👁️ {{ blog.views || 0 }} · ❤️ {{ blog.likes || 0 }}
                        </span>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 分页控制 -->
                <div v-if="pagination.total > pagination.pageSize" class="pagination">
                  <button
                    :disabled="pagination.current <= 1"
                    @click="handlePageChange(pagination.current - 1)"
                  >
                    上一页
                  </button>

                  <span class="page-info">
                    第 {{ pagination.current }} 页，共
                    {{ Math.ceil(pagination.total / pagination.pageSize) }} 页
                  </span>

                  <button
                    :disabled="
                      pagination.current >= Math.ceil(pagination.total / pagination.pageSize)
                    "
                    @click="handlePageChange(pagination.current + 1)"
                  >
                    下一页
                  </button>
                </div>
              </div>
            </div>
          </div>

          <div v-else class="no-selection">
            <p>请选择一个分类查看详情</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
  .category-list-page {
    min-height: 100vh;
    padding: 2rem 0;
    background-color: var(--bg-color);
  }

  .page-header {
    text-align: center;
    margin-bottom: 2rem;

    .page-title {
      font-size: 2.5rem;
      font-weight: 700;
      color: var(--text-primary);
      margin: 0 0 0.5rem 0;
    }

    .page-subtitle {
      font-size: 1.1rem;
      color: var(--text-secondary);
      margin: 0;
    }
  }

  .loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 4rem 0;

    .loading-spinner {
      width: 40px;
      height: 40px;
      border: 3px solid var(--border-color);
      border-top: 3px solid var(--primary-color);
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-bottom: 1rem;
    }
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }

  .main-content {
    display: grid;
    grid-template-columns: 300px 1fr;
    gap: 2rem;
    align-items: start;
    min-height: 600px;
  }

  /* 左侧分类树 */
  .categories-sidebar {
    background: var(--bg-color);
    border: 1px solid var(--border-color);
    border-radius: var(--radius-xl);
    height: fit-content;
    max-height: 80vh;
    overflow-y: auto;
    position: sticky;
    top: calc(56px + 2rem); /* 头部高度 + 间距 */

    .sidebar-header {
      padding: 1.5rem;
      border-bottom: 1px solid var(--border-color);

      h3 {
        font-size: 1.2rem;
        font-weight: 600;
        color: var(--text-primary);
        margin: 0 0 0.5rem 0;
      }

      .category-count {
        font-size: 0.9rem;
        color: var(--text-secondary);
        margin: 0;
      }
    }

    .categories-tree {
      padding: 1rem 0;
    }
  }

  .category-tree-node {
    .category-node {
      display: flex;
      align-items: center;
      gap: 0.5rem;
      padding: 0.5rem 1rem;
      cursor: pointer;
      transition: all 0.2s ease;
      position: relative;

      &:hover {
        background: var(--bg-secondary);
      }

      &.selected {
        background: var(--primary-color);
        color: white;

        .category-count {
          color: rgba(255, 255, 255, 0.8);
        }
      }

      .tree-line {
        position: absolute;
        left: calc(var(--depth, 0) * 1.5rem + 0.5rem);
        top: 0;
        bottom: 0;
        width: 1px;
        background: var(--border-color);

        &::before {
          content: '';
          position: absolute;
          top: 50%;
          left: 0;
          width: 1rem;
          height: 1px;
          background: var(--border-color);
        }
      }

      .expand-icon {
        width: 1.2rem;
        height: 1.2rem;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 2px;
        font-size: 0.8rem;
        font-weight: bold;
        background: var(--bg-secondary);
        color: var(--text-secondary);
        flex-shrink: 0;

        &:hover {
          background: var(--primary-color);
          color: white;
        }
      }

      .category-icon {
        font-size: 1rem;
        flex-shrink: 0;
      }

      .category-name {
        flex: 1;
        font-size: 0.9rem;
        font-weight: 500;
        min-width: 0;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .category-count {
        font-size: 0.8rem;
        color: var(--text-secondary);
        flex-shrink: 0;
      }
    }
  }

  /* 右侧详情面板 */
  .category-detail-panel {
    background: var(--bg-color);
    border: 1px solid var(--border-color);
    border-radius: var(--radius-xl);
    min-height: 600px;

    .detail-content {
      padding: 2rem;
    }

    .no-selection {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 400px;
      color: var(--text-secondary);
      font-size: 1.1rem;
    }
  }

  /* 分类信息区域 */
  .category-info-section {
    margin-bottom: 2rem;

    .category-header {
      .category-title {
        display: flex;
        align-items: center;
        gap: 1rem;
        margin-bottom: 1rem;

        .category-icon-large {
          font-size: 2rem;
        }

        h2 {
          font-size: 1.8rem;
          font-weight: 600;
          color: var(--text-primary);
          margin: 0;
        }
      }

      .category-path {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        margin-bottom: 1rem;
        font-size: 0.9rem;
        color: var(--text-secondary);

        .path-label {
          font-weight: 500;
        }

        .path-item {
          color: var(--text-primary);

          &.clickable {
            color: var(--primary-color);
            cursor: pointer;
            text-decoration: underline;
            text-decoration-color: transparent;
            transition: all 0.2s ease;

            &:hover {
              text-decoration-color: var(--primary-color);
              background-color: var(--primary-light);
              padding: 0.2rem 0.4rem;
              border-radius: var(--radius-sm);
              margin: -0.2rem -0.4rem;
            }
          }

          &:last-child {
            font-weight: 600;
            color: var(--text-primary);
          }
        }

        .path-separator {
          margin: 0 0.25rem;
          color: var(--text-secondary);
        }
      }

      .category-stats {
        display: flex;
        gap: 2rem;

        .stat-item {
          display: flex;
          align-items: center;
          gap: 0.5rem;

          .stat-label {
            font-size: 0.9rem;
            color: var(--text-secondary);
          }

          .stat-value {
            font-size: 1rem;
            font-weight: 600;
            color: var(--primary-color);
          }
        }
      }
    }
  }

  /* 子分类网格 */
  .subcategories-section {
    margin-bottom: 2rem;
    padding-bottom: 2rem;
    border-bottom: 1px solid var(--border-color);

    .section-title {
      font-size: 1.3rem;
      font-weight: 600;
      color: var(--text-primary);
      margin: 0 0 1rem 0;
    }

    .subcategories-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 1rem;
    }

    .subcategory-card {
      display: flex;
      align-items: center;
      gap: 1rem;
      padding: 1rem;
      background: var(--bg-secondary);
      border: 1px solid var(--border-color);
      border-radius: var(--radius-lg);
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        border-color: var(--category-color);
        background: var(--category-color);
        color: white;
        transform: translateY(-2px);

        .subcategory-count {
          color: rgba(255, 255, 255, 0.8);
        }
      }

      .subcategory-icon {
        font-size: 1.5rem;
        flex-shrink: 0;
      }

      .subcategory-info {
        flex: 1;
        min-width: 0;

        .subcategory-name {
          font-size: 1rem;
          font-weight: 500;
          margin: 0 0 0.25rem 0;
          color: var(--text-primary);
        }

        .subcategory-count {
          font-size: 0.8rem;
          color: var(--text-secondary);
        }
      }
    }
  }

  /* 文章列表区域 */
  .articles-section {
    .articles-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 1.5rem;
      flex-wrap: wrap;
      gap: 1rem;

      .section-title {
        font-size: 1.3rem;
        font-weight: 600;
        color: var(--text-primary);
        margin: 0;
      }

      .articles-controls {
        display: flex;
        align-items: center;
        gap: 1rem;

        .search-box {
          display: flex;
          align-items: center;
          background: var(--bg-secondary);
          border: 1px solid var(--border-color);
          border-radius: var(--radius-lg);
          overflow: hidden;

          input {
            padding: 0.5rem 1rem;
            border: none;
            background: transparent;
            color: var(--text-primary);
            font-size: 0.9rem;
            width: 200px;

            &::placeholder {
              color: var(--text-secondary);
            }

            &:focus {
              outline: none;
            }
          }

          button {
            padding: 0.5rem 1rem;
            border: none;
            background: var(--primary-color);
            color: white;
            cursor: pointer;
            transition: background 0.3s ease;

            &:hover {
              background: var(--primary-color-dark);
            }
          }
        }

        .sort-select {
          .custom-select {
            position: relative;
            min-width: 120px;

            .select-trigger {
              display: flex;
              align-items: center;
              justify-content: space-between;
              padding: 0.6rem 1rem;
              background: var(--bg-secondary);
              border: 1px solid var(--border-color);
              border-radius: var(--radius-lg);
              cursor: pointer;
              transition: all 0.3s ease;

              &:hover {
                border-color: var(--primary-color);
                background: var(--bg-tertiary);
              }

              .select-text {
                font-size: 0.9rem;
                color: var(--text-primary);
                font-weight: 500;
              }

              .select-arrow {
                font-size: 0.7rem;
                color: var(--text-secondary);
                transition: transform 0.3s ease;

                &.open {
                  transform: rotate(180deg);
                  color: var(--primary-color);
                }
              }
            }

            .select-dropdown {
              position: absolute;
              top: 100%;
              left: 0;
              right: 0;
              background: var(--bg-color);
              border: 1px solid var(--border-color);
              border-radius: var(--radius-lg);
              box-shadow: var(--shadow-lg);
              z-index: 100;
              margin-top: 0.25rem;
              overflow: hidden;
              animation: dropdownSlide 0.2s ease-out;

              .select-option {
                display: flex;
                align-items: center;
                gap: 0.5rem;
                padding: 0.75rem 1rem;
                cursor: pointer;
                transition: all 0.2s ease;

                &:hover {
                  background: var(--bg-secondary);
                }

                &.selected {
                  background: var(--primary-light);
                  color: var(--primary-color);

                  .option-icon {
                    filter: brightness(1.2);
                  }
                }

                .option-icon {
                  font-size: 1rem;
                  flex-shrink: 0;
                }

                .option-text {
                  font-size: 0.9rem;
                  font-weight: 500;
                }
              }
            }
          }
        }
      }
    }

    .articles-loading {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 3rem 0;

      .loading-spinner {
        width: 30px;
        height: 30px;
        border: 2px solid var(--border-color);
        border-top: 2px solid var(--primary-color);
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin-bottom: 1rem;
      }
    }

    .articles-empty {
      text-align: center;
      padding: 3rem 0;
      color: var(--text-secondary);
    }

    .articles-items {
      display: flex;
      flex-direction: column;
      gap: 1rem;
    }

    .article-item {
      padding: 1.5rem;
      background: var(--bg-secondary);
      border: 1px solid var(--border-color);
      border-radius: var(--radius-lg);
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        border-color: var(--primary-color);
        background: var(--bg-tertiary);
        transform: translateY(-2px);
      }

      .article-content {
        .article-title {
          font-size: 1.1rem;
          font-weight: 600;
          color: var(--text-primary);
          margin: 0 0 0.5rem 0;
          line-height: 1.4;
        }

        .article-summary {
          font-size: 0.9rem;
          color: var(--text-secondary);
          line-height: 1.5;
          margin: 0 0 1rem 0;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          line-clamp: 2;
          overflow: hidden;
          -webkit-box-orient: vertical;
        }

        .article-meta {
          display: flex;
          align-items: center;
          gap: 1rem;
          font-size: 0.8rem;
          color: var(--text-secondary);

          .article-category {
            background: var(--primary-color);
            color: white;
            padding: 0.2rem 0.6rem;
            border-radius: var(--radius-sm);
          }

          .article-date,
          .article-stats {
            color: var(--text-secondary);
          }
        }
      }
    }

    .pagination {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 1rem;
      margin-top: 2rem;
      padding-top: 2rem;
      border-top: 1px solid var(--border-color);

      button {
        padding: 0.5rem 1rem;
        border: 1px solid var(--border-color);
        background: var(--bg-secondary);
        color: var(--text-primary);
        border-radius: var(--radius-lg);
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover:not(:disabled) {
          border-color: var(--primary-color);
          background: var(--primary-color);
          color: white;
        }

        &:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }
      }

      .page-info {
        font-size: 0.9rem;
        color: var(--text-secondary);
      }
    }
  }

  /* 响应式设计 */
  @media (max-width: 1024px) {
    .main-content {
      grid-template-columns: 250px 1fr;
    }
  }

  @media (max-width: 768px) {
    .main-content {
      grid-template-columns: 1fr;
      gap: 1rem;
    }

    .categories-sidebar {
      position: static;
      max-height: 300px;
    }

    .page-header .page-title {
      font-size: 2rem;
    }

    .articles-header {
      flex-direction: column;
      align-items: stretch;

      .articles-controls {
        justify-content: space-between;
      }
    }

    .subcategories-grid {
      grid-template-columns: 1fr;
    }

    .category-stats {
      flex-direction: column;
      gap: 0.5rem !important;
    }
  }

  @media (max-width: 480px) {
    .category-list-page {
      padding: 1rem 0;
    }

    .detail-content {
      padding: 1rem !important;
    }

    .articles-controls {
      flex-direction: column;
      align-items: stretch !important;

      .search-box input {
        width: 100%;
      }
    }
  }

  @keyframes dropdownSlide {
    from {
      opacity: 0;
      transform: translateY(-10px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
</style>
